package csvm_v2.components;

import com.sun.corba.se.impl.orbutil.concurrent.Mutex;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * DaemonComponent adalah kelas abstrak bagi komponen vending machine yang aktif
 * dan dijalankan dalam sebuah thread
 *
 * @author Muqtafi Akhmad
 */
public abstract class DaemonComponent implements Runnable {

    private Mutex attrMutex;
    private boolean isDone;

    public DaemonComponent() {
        attrMutex = new Mutex();
        isDone = false;
    }

    @Override
    public void run() {
        while (!isDone) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(DaemonComponent.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("Shutdown daemon component");
    }

    public void done() {
        isDone = true;
    }

    public void grabResource() {
        try {
            attrMutex.acquire();
        } catch (InterruptedException ex) {
            Logger.getLogger(DaemonComponent.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void releaseResource() {
        attrMutex.release();
    }
}
